﻿using System.Data.OleDb;

namespace DimensionsHelper.Client.WinUi.Helpers;

public static class DataCollectionHelper
{
    public const string DbProviderDescription = "IBM SPSS Data Collection DM-2 OLE DB Provider";

    private const string DbProvider = "mrOleDB.Provider.2";


    static DataCollectionHelper()
    {
        OleDbDataReader enumerator = OleDbEnumerator.GetRootEnumerator();
        // 查找是否安装了 mrOleDB.Provider
        IsDataCollectionFound = false;
        foreach (IDataRecord record in enumerator.Cast<IDataRecord>())
        {
            if (record["SOURCES_NAME"].ToString() == "mrOleDB.Provider")
            {
                IsDataCollectionFound = true;
                break;
            }
        }
    }


    public static bool IsDataCollectionFound
    {
        get;
        private set;
    }


    public static string
        BuildConnectionString(string metadataPath, string casedataPath,
            DataCollectionQueryCategoryDataType categoryType) =>
        $"Provider = {DbProvider}; Data Source = mrDataFileDsc; MR Init MDM Version = {{ }}; MR Init Access = 1; MR Init Category Names = {(int)categoryType}; Initial Catalog = {metadataPath}; Location={casedataPath}";


    public static string BuildQueryString(string? fields, string? query) =>
        $"Select {(string.IsNullOrEmpty(fields) ? "*" : fields)} From vdata{(string.IsNullOrEmpty(query) ? "" : " " + query)}";


    public static async Task LoadDataAsync(string connetionString, string? fields, string? query, DataSet targetSet,
        string tableName)
    {
        using OleDbConnection connection = new(connetionString);
        using OleDbCommand command = connection.CreateCommand();
        command.CommandText = BuildQueryString(fields, query);

        try
        {
            await connection.OpenAsync();
            using OleDbDataAdapter adapter = new(command);
            adapter.Fill(targetSet, tableName);
        }
        finally
        {
            await connection.CloseAsync();
        }
    }
}

public enum DataCollectionQueryCategoryDataType
{
    Value,
    Name
}